package com.yupi.springbootinit.service.impl;

import cn.hutool.json.JSONUtil;
import com.yupi.springbootinit.model.entity.Picture;
import com.yupi.springbootinit.service.PictureService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 图片服务实现类
 */
@Service
public class PictureServiceImpl implements PictureService {

    /**
     * 将请求转发到微软必应搜索中去搜索图片
     * @param searchText  搜索关键词
     * @param pageNum
     * @param pageSize
     * @return
     * @throws IOException
     */
    @Override
    public List<Picture> searchPictures(String searchText, long pageNum, long pageSize) throws IOException {
        //拼接查询页码
        long current = (pageNum - 1) * pageSize;
        //借助微软bing搜索的方式来搜索图片（第三方库：jsoup）
        String url = String.format("https://cn.bing.com/images/search?q=%s&form=HDRSC2&first=%d",searchText,current);
        Document doc = Jsoup.connect(url).get();

        //解析返回的html页面中的元素，将图片url与图片标题拿到
        Elements elements = doc.select(".iuscp.isv");
        List<Picture> pictureList = new ArrayList<>();
        for (Element element : elements) {
            //获取图片地址(murl)
            String m = element.select(".iusc").get(0).attr("m");
            //将这个返回json字符串进行解析
            Map<String,Object> map = JSONUtil.toBean(m, Map.class);
            //得到地址
            String murl = (String) map.get("murl");

            //获取图片标题
            String title = elements.select(".inflnk").get(0).attr("aria-label");

            //封装数据
            Picture picture = new Picture();
            picture.setUrl(murl);
            picture.setTitle(title);
            //添加列表中
            pictureList.add(picture);
            if (pictureList.size() == (int) pageSize){
                break;
            }
        }
        //返回整理好的图片资源集合
        return pictureList;
    }
}
